package net.zoneland.knowledge.service.impl;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

import net.zoneland.knowledge.constant.BizConstant;
import net.zoneland.knowledge.model.WorkApplyInfo;
import net.zoneland.knowledge.service.NotifyService;
import net.zoneland.knowledge.utils.DateHelper;
import net.zoneland.uniflow.client.TaskObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.constant.ApproveConstant;
import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.dao.DictItemMapper;
import net.zoneland.knowledge.service.EmailService;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class EmailServiceImpl<T, K> implements EmailService<T, K> {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private DictItemMapper dictItemMapper;

    @Autowired
    private NotifyService notifyService;

    @Override
    public void sendEmail(final Consumer<Map<String, Object>> sendFunction, final T t, final K k) {
        //获取是否发送邮件。0否，1是。数据字典里是emailSend。
        String dictName = dictItemMapper.getDictNameByValue("emailSend", "email");
        if ("0".equals(dictName)) {
            LOGGER.info("数据字典为0，不发送邮件");
            return;
        }
        //获取邮件转发人，如果有就转发，没有就默认。数据字典里是emailSend。
        String emailLeader = dictItemMapper.getDictNameByValue("emailLeader", "email");
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.EMAIL_LEADER, emailLeader);
        map.put(Constants.PARAM, t);
        map.put(ApproveConstant.WORK_APPLY_INFO, k);
        sendFunction.accept(map);
    }

    /**
     * 发送邮件.
     * @param sendFunction
     * @param t
     */
    @Override
    public void sendEmail(final Consumer<Map<String, Object>> sendFunction, final T t) {
        sendEmail(sendFunction, t, null);
    }

    @Override
    public void sendEmailFunction(final String titleTemplate,final String contentTemplate, final String flowType,final String taskUrl,
                                  final Map<String, Object> map) {
        final TaskObject[] tasks = (TaskObject[]) map.get(Constants.PARAM);
        final String emailLeader = (String) map.get(Constants.EMAIL_LEADER);
        final String[] chapterAdmin = (String[]) map.get(Constants.ROLE_CHAPTER_ADMIN);
        final String[] copySubmitUser = (String[]) map.get(Constants.ROLE_COPY_SUBMIT_USER);
        final WorkApplyInfo workApplyInfo = (WorkApplyInfo) map.get(ApproveConstant.WORK_APPLY_INFO);
        final String title = MessageFormat.format(titleTemplate, new String[] {workApplyInfo.getTitle()});
        final UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(taskUrl).
                path("/index/talk.htm");
        if(ArrayUtils.isNotEmpty(copySubmitUser)){
            // 抄送待阅邮件
            String url = urlBuilder.replaceQueryParam("toReadParam", workApplyInfo.getId()).build().toString();
            String createTime = DateFormatUtils.format(workApplyInfo.getCreateTime(), DateHelper.DATE_PATTERN_WITHOUT_SECOND);
            String content = MessageFormat.format(contentTemplate, new String[]{url, workApplyInfo.getTitle(),
                    workApplyInfo.getCreatorName(), createTime});

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("mail title:{},mail receiver:{},mail content:{}", title, copySubmitUser, content);
            }

            notifyService.notifyByEmail(copySubmitUser, title, content);
        }else {
            Arrays.stream(tasks).forEach(taskObject -> {
                // 链接参数：发送给印章管理员的为已办,通过id查询(chapterApply:{id}), 其他为待办查询(chapterApply-{wiid})
                String urlParam = Objects.nonNull(chapterAdmin) ? Constants.STRING_SPLIT_FLAG_COLON + workApplyInfo.getId() : Constants.STRING_SPLIT_FLAG_SUB_LINE + taskObject.getTiid();
                String url = urlBuilder.replaceQueryParam("todoParam",flowType + urlParam).build().toString();
                String createTime = DateFormatUtils.format(workApplyInfo.getCreateTime(), DateHelper.DATE_PATTERN_WITHOUT_SECOND);
                if (BizConstant.CHAPTER_APPLY_PROCESS_CODE.equals(flowType)){
                    createTime = DateFormatUtils.format(workApplyInfo.getChapterDate(), DateHelper.DATE_PATTERN_WITHOUT_SECOND);
                }
                String content = MessageFormat.format(contentTemplate, new String[]{url, workApplyInfo.getTitle(),
                        workApplyInfo.getCreatorName(), createTime});
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("mail title:{},mail receiver:{},mail content:{}", title,
                            Objects.nonNull(taskObject.getOwner()) ? taskObject.getOwner().getUserId() : taskObject.getOwner(), content);
                }
                if (StringUtils.isNotBlank(emailLeader)) {
                    notifyService.notifyByEmail(new String[]{emailLeader}, title, content);
                } else if (Objects.nonNull(chapterAdmin)) {
                    // 发送给印章管理员
                    notifyService.notifyByEmail(chapterAdmin, title, content);
                } else {
                    notifyService.notifyByEmail(new String[]{taskObject.getOwner().getUserId()}, title, content);
                }
            });
        }

    }

    /**
     * 指定人员发送邮件.
     * @param sendFunction  Consumer<Map<String, Object>>.
     * @param t 参数
     * @param k 工单信息参数名
     * @param role 接收人员角色
     * @param managers 接收人员
     */
    @Override
    public void sendEmail(Consumer<Map<String, Object>> sendFunction, T t, K k, String role, String[] managers) {
        //获取是否发送邮件。0否，1是。数据字典里是emailSend。
        String dictName = dictItemMapper.getDictNameByValue("emailSend", "email");
        if ("0".equals(dictName)) {
            LOGGER.info("数据字典为0，不发送邮件");
            return;
        }
        if (ArrayUtils.isEmpty(managers)) {
            LOGGER.error("缺少邮件接收人信息，取消发送邮件");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(role, managers);
        map.put(Constants.PARAM, t);
        map.put(ApproveConstant.WORK_APPLY_INFO, k);
        sendFunction.accept(map);
    }

    @Override
    public void sendEmailFunctionForIssued(final String titleTemplate,final String contentTemplate, final String flowType,final String taskUrl,
                                  final Map<String, Object> map) {
        final String[] issuedUsers = (String[]) map.get(Constants.ROLE_ISSUED_USER);
        final UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(taskUrl).
                path("/index/talk.htm");
        final String url = urlBuilder.replaceQueryParam("workReminder", flowType).build().toString();
        final String content = MessageFormat.format(contentTemplate, new String[]{url});

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("mail title:{},mail receiver:{},mail content:{}", titleTemplate, issuedUsers, content);
        }

//        notifyService.notifyByEmail(issuedUsers, titleTemplate, content);

    }


    /**
     * 获取 dictItemMapper.
     *
     * @return dictItemMapper
     */
    public DictItemMapper getDictItemMapper() {

        return dictItemMapper;
    }

    /**
     * 设置 dictItemMapper.
     *
     * @param dictItemMapper dictItemMapper
     */
    public void setDictItemMapper(final DictItemMapper dictItemMapper) {

        this.dictItemMapper = dictItemMapper;
    }

}
